home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: Philip Staite <pstaite+@rchland.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: C++ problem with constructor.
- Date: Wed, 20 Mar 1996 15:16:31 -0600
- Organization: IBM Rochester, MN
- Message-ID: <315075AF.2781@rchland.ibm.com>
- References: <DoGGGp.Muy@latcs1.lat.oz.au>
- NNTP-Posting-Host: powertool.rchland.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (X11; I; AIX 1)
-
- Gregary J Boyles wrote:
-
- Basically the problem is you never get storage for your strings. This
- comes down to fundamental string handling. You can do this over and
- over again in every class you design that uses strings :-( Or you can
- use a string class and merely use string objects. To deomonstrate this,
- I've modified your code with a simple buffer class that encapsulates
- string memory management. This code is just hacked out off the top of
- my head, but should be pretty close.
-
- // address.cpp
-
- #include "address.h"
- #include <string.h>
-
- // Constructors
- Address::Address(int ANumber,const char *AStreet,const char *ACity,int
- AZip)
- {
- Number=ANumber;
- Street = AStreet;
- City = ACity;
- Zip=AZip;
- }
-
- Address::Address()
- {
- Number=0;
-
-
- Zip=0;
- }
- >
- > // Copy constructor
- > Address::Address(Address& AnAddress)
- > {
- > Number=AnAddress.Number;
- Street = AnAddress.Street;
- City = AnAddress.City;
- > Zip=AnAddress.Zip;
- > }
- >
- > // Deconstructor
- > Address::~Address()
- > {
- > Number=0;
-
-
- > Zip=0;
- > }
- >
- > // address.h
- >
- > #ifndef __ADDRESS_H
- > #define __ADDRESS_H
- > #define STR_STREET " street"
- >
- > #include "defines.h"
-
- char* dupe( const char* p ) {
- if( ! p )
- return 0;
- return strcpy( new char[ strlen( p ) + 1 ], p ); }
-
-
- class buf {
- public:
- buf( const char* s = 0 ) : p( dupe( s ) ) {}
- buf( const buf& b ) : p( dupe( b.p ) ) {}
- ~buf() { delete[] p; }
- buf& operator=( const buf& b ) { delete[] p; p = dupe( b.p ); return
- *this; }
- buf& operator=( const char* s ) { delete[] p; p = dupe( s ); return
- *this; }
- operator char*() { return p; }
- operator const char*() const { return p; }
- private:
- char* p;
- };
-
- > class Address
- > {
- > private : int Number;
- buf Street,
- City;
- > int Zip;
- >
- > public : // Constructors
- > Address(int ANumber,const char *AStreet,const char *ACity,int Zip);
- > Address();
- > // Copy constructor
- > Address(Address& AnAddress);
- > // Deconstructor
- > ~Address();
- > };
- >
- > #endif
-
- --
-
- Phil Staite, (507) 253-2529, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-